from random import randint

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.test2
collection = db["example"]
print(f"mongodb连接成功，数据库为{db.name}")
print(f"mongodb连接成功，数据库表为{collection.name}")

data = {
    "name": "张三",
    "age": 18,
    "sex": "男"
}
collection.insert_one(data)
print("数据插入成功")
print([d for d in collection.find()])

# 修改数据
for d in collection.find():
    new_age = randint(10, 20)
    collection.update_many(
        {"_id": d["_id"], "age": {"$ne": 11}},
        {"$set": {"age": new_age}}
    )
client.close()
